/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Usuario;

import Model.User;
import com.google.gson.Gson;
import java.util.ArrayList;
import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import org.hibernate.Session;

/**
 *
 * @author pedro
 */
@Path("/usuarios")
public class ListaUsuarios {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getUser() {

        Session session = HibernateUtil.getSession();
        HibernateUtil.beginTransaction();
        ArrayList<User> lista = (ArrayList<User>) session.createQuery("From User").list();

        HibernateUtil.commitTransaction();
        HibernateUtil.closeSession();

        Gson g = new Gson();
        String teste = g.toJson(lista);

        return teste;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public Response getUserParam(User user) {

        String resultado;
        Session session = null;
        Gson g = new Gson();
        try {
            session=HibernateUtil.getSession();
            HibernateUtil.beginTransaction();
            ArrayList<User> lista = (ArrayList<User>) session.createQuery("From User Where nome like :nome")
                    .setParameter("nome", '%' + user.getNome() + '%')
                    .list();
            HibernateUtil.commitTransaction();

            resultado = g.toJson(lista);
        } catch (Exception e) {
            System.out.println(e);
            resultado = "Error";
            session.getTransaction().rollback();
        } finally {
            try {
                HibernateUtil.closeSession();
            } catch (Throwable e) {
                System.out.println(e.getMessage());
            }
        }
       return Response.status(201).entity(resultado).build();
    }
}
